/**
 * 阅读量/点赞量
 * 1.Keyword.findAllKeywords 获得单个keyword
 * 2.Wechat.findByKeyword 获得匹配文章
 * 3.根据日期统计
 */
var Wechat = require('../../models/wechat/scrapyModel').Wechat;
var WechatStat = require('../../models/wechat/statModel').WechatStat;
var Keyword = require('../../models/keywordsModel').Keyword;
var Util = require('../../util/util');

function main() {
    console.log('===============  微信 阅读量/点赞量 统计 开始');
    FindAllKeywords();
}

function FindAllKeywords(){
    Keyword.findAllKeywords(function (err, docs) {
        var list = [];
        if (err) {
            console.log(err);
        }
        for (var i in docs) {
            list.push({
                'keyword_id': docs[i]._id,
                'title': docs[i].title
            })
        }
        ListForEach(list,function(){
            console.log('微信 阅读量/点赞量 统计 所有完成了！！');
        })

    });
}

function ListForEach(list,callback){
    //同步
    var i,getTitle,findByTitle,hashDate,initExport,insertStat,next,done;
    i = 0;

    getTitle = function(){
        if(i>=list.length){
            return done();
        }
        console.log('获取题目....'+list[i].title);
        findByTitle(list[i]);
    };

    findByTitle = function(list){
        Wechat.findByKeyword(list.title,function(err,data){
            console.log('获取'+list.title+'的数据长度....'+data.length);
            hashDate(list,data);
        });
    };

    hashDate = function(list,data){
        console.log(list.title+'Data...');
        var tempData = {};
        for(var d in data){
            var unixTimestamp = data[d].post_time;
            var commonTime = new Date(unixTimestamp).Format("yyyy/MM/dd");
            var hashMap = new Util.HashMap();
            if(!hashMap.Contains(commonTime)){
                //not exist
                hashMap.Set(commonTime,commonTime);
                tempData[commonTime] = {
                    'date': commonTime,
                    'read_num': parseInt(data[d].read_num),
                    'like_num': parseInt(data[d].like_num)
                }
            }
            else {
                //exist
                tempData[commonTime].read_num += Number(parseInt(data[d].read_num));
                tempData[commonTime].like_num += Number(parseInt(data[d].like_num));
            }
        }
        initExport(list,tempData);

    };

    initExport = function(list,temp){
        var exportData=[];
        if(temp){
            for (var t in temp) {
                exportData.push(temp[t])
            }
        }
        insertStat(list,exportData);

    };

    insertStat = function(list,exportData){
        //console.log(exportData);
        WechatStat.savePlaylike(list.keyword_id,list.title,exportData);
        next(list);
    };

    next = function(list){
        console.log('已经完成啦....'+list.title);
        ++i;
        getTitle();
    };

    done = function(){
        callback();
    };

    return getTitle();
}


exports.main = main;

